// 链接参数对象转字符串
export const param2str = function (obj, sort = false) {
  if (!(obj && obj.toString() === '[object Object]')) return ''
  let str = ''
  let keys = Object.keys(obj)

  if (sort) {
    keys = keys.sort()
  }

  keys.forEach((p) => {
    str += `${str ? '&' : '?'}${p}=${obj[p]}`
  })

  return str
}

// 链接传参数对象
export const str2param = function (url) {
  if (!url || typeof url !== 'string') return url
  let arr = url.split('?')

  let search = arr[arr.length - 1]
  search = search.split('&')
  let obj = {}
  for (let i = 0; i < search.length; i++) {
    let item = search[i]
    let index = item.indexOf('=')
    let key = item.substring(0, index)
    let value = item.substring(index + 1, item.length)
    if (key !== '') {
      obj[key] = value
    }
  }
  return obj
}

// 过滤链接参数
export const filterUrlParams = function (url, keys = ['token']) {
  if (!keys) return

  let arr = []

  if (Array.isArray(keys)) {
    arr = keys
  } else {
    arr = [keys]
  }

  let query = str2param(url) || {}
  let href = url.indexOf('?') === -1 ? url : url.split('?')[0]

  arr.forEach((v) => {
    delete query[v]
  })

  return href + param2str(query)
}

// 过滤公众号授权参数
export const filterUrlWxAuthParams = function (url, data = ['uniqueCheck']) {
  let arr = [
    'access_token',
    'refresh_token',
    'openid',
    'scope',
    'expires_in',
    'sign',
    'unionid',
    ...data
  ]
  return filterUrlParams(url, arr)
}
